<?php
/**
 * @Author: Xu Liu email:2867557054@qq.com
 * @Date:   2016-12-23 13:28:33
 * @Last Modified by:   Xu Liu
 * @Last Modified time: 2018-01-03 23:04:42
 */
if (!defined('IN_DISCUZ')) {
    exit('Access Denid');
}
class table_jamesonread_search extends discuz_table
{

    public function __construct()
    {
        $this->_table         = 'jamesonread_search';
        $this->_pk            = 'id';
        $this->_pre_cache_key = 'jamesonreadsearch_';
        $this->_cache_ttl     = 300;
        parent::__construct();
    }
    public function fetch_tag_paihang($size = 20)
    {
        if ($cache = $this->fetch_cache('paihang_' . $size)) {
            return $cache;
        }
        $data = DB::fetch_all('SELECT * FROM ' . DB::table($this->_table) . ' WHERE tagcounts > 0 AND NOT ' . DB::field('tag', '%?%', 'like') . ' ORDER BY tagcounts DESC LIMIT ' . intval($size));
        foreach ($data as $key => $value) {
            if(mb_strlen($value['tag']) < 3 || preg_match("/\./",$value['tag'])){
                unset($data[$key]);
            }
        }
        if ($data) {
            $this->store_cache('paihang_' . $size, $data);
        }
        return $data;
    }
    public function addkeyword($keyword, $type = 'keyword')
    {
        if (preg_match('/\?/', $keyword)) {
            return false;
        }
        $type = trim(strtolower($type));
        $jl   = DB::fetch_first('SELECT * FROM %t WHERE ' . DB::field($type, $keyword), array($this->_table));
        if (!$jl) {
            $this->insert(array(
                'keyword'   => $keyword,
                'tag'       => $keyword,
                'counts'    => ($type == 'keyword') ? 1 : 0,
                'tagcounts' => ($type == 'keyword') ? 0 : 1,
                'addtime'   => TIMESTAMP,
            ));
        } else {
            if ($type == 'keyword') {
                $data = array(
                    'counts' => 1 + intval($jl['counts']),
                );
            } else {
                $data = array(
                    'tagcounts' => 1 + intval($jl['tagcounts']),
                );
            }
            $this->update($jl['id'], $data);
        }
    }
    public function fetch_by_keyword($keyword)
    {
        return DB::fetch_first('SELECT * FROM %t WHERE ' . DB::field('keyword', $keyword), array($this->_table));
    }
    public function fetch_by_counts($num)
    {
        if ($cache = $this->fetch_cache('counts_' . $num)) {
            return $cache;
        }
        $data = DB::fetch_all('SELECT * FROM %t WHERE counts>%d ORDER BY counts DESC LIMIT %d ', array($this->_table, 0, $num));
        if ($data) {
            $this->store_cache('counts_' . $size, $data);
        }
        return $data;
    }
}